package com.bosssoft.trainee.until;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author liuqiang
 * @date 2022/7/6 15:15
 */
@Slf4j
@Component
public class JwtUntil {

    //加密 解密时的密钥 用来生成key
    public static final String JWT_KEY = "admin123";


    public static JWTVerifier parseJWT() {

        JWTVerifier jwtVerifier;
        jwtVerifier = JWT.require(Algorithm.HMAC256(JWT_KEY)).build();
        return jwtVerifier;
    }

    public static String getUserId(String token) {
        return JWT.decode(token).getAudience().get(0);
    }


    /**
     * 解析jwt
     */
    public static Map<String, Claim> parseJwt(String token) {
        Map<String, Claim> claims = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_KEY);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            claims = jwt.getClaims();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }
}
